/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource.image;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ContentImage;
import com.blandware.atleap.service.core.ContentResourceManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ImageForm;
import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
import com.blandware.atleap.webapp.util.core.*;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.apache.commons.validator.GenericValidator;

import javax.imageio.IIOImage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletContext;
import java.util.List;

/**
 * <p>Prepares form bean to update image
 * </p>
 * <p><a href="CallUpdateImageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.13 $ $Date: 2007/12/11 14:23:47 $
 * @struts.action path="/core/contentResource/image/callUpdate"
 * name="imageForm"
 * scope="request"
 * validate="false"
 * roles="core-contentResource-update"
 * @struts.action-forward name="updateImage"
 * path=".core.contentResource.image.update"
 * @struts.action-forward name="callUpdateContentResource"
 * path="/core/contentResource/callUpdate.do"
 * @struts.action-forward name="listContentResources"
 * path="/core/contentResource/list.do"
 * redirect="false"
 */
public final class CallUpdateImageAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();
        ServletContext servletContext = session.getServletContext();

        String requestUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);
        
        Long contentResourceId = null;
		if ( ((ImageForm) form).getId() != null ) {
			contentResourceId = Long.valueOf(((ImageForm) form).getId());
		} else if ( request.getParameter("contentResourceId") != null ) {
			contentResourceId = Long.valueOf(request.getParameter("contentResourceId"));
		} else if ( request.getAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY) != null ) {
			contentResourceId = (Long) request.getAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing required parameter 'contentResourceId'");
			}
			return mapping.getInputForward();
		}

		ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
		ContentImage image = contentResourceManager.retrieveContentImage(contentResourceId);
		if ( image == null ) {
			// image not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("imageNotFound", new ActionMessage("core.contentResource.image.errors.notFound"));
			saveErrors(request, errors);
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}

		request.setAttribute("image", image);

		ImageForm imageForm = (ImageForm) form;
		WebappUtil.copyProperties(imageForm, image, request);
        imageForm.setDescriptionMap(image.getDescription());

        //setup uri
		String uri = image.getUri();
		if ( uri.startsWith(Constants.RESOURCES_URI_PREFIX) ) {
			uri = uri.substring(Constants.RESOURCES_URI_PREFIX.length());
		}
		imageForm.setUri(uri);

        ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(servletContext);

		UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) session
                .getAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
		FormFile formFile = null;
		if ( uploadContentResourceForm != null ) {
			formFile = uploadContentResourceForm.getFile();
		}
		if ( formFile != null && formFile.getFileName() != null && formFile.getFileName().trim().length() > 0 && formFile.getFileSize() > 0 ) {
			String fileName = formFile.getFileName();
			String mimeType = resourceTypesManager.getMimeTypeByFileName(fileName);

			byte[] newImageData = formFile.getFileData();

			try {
				IIOImage newSource = ImageUtil.decodeImage(newImageData, mimeType);
				session.setAttribute(WebappConstants.CONTENT_IMAGE_NEW_WIDTH_KEY, new Integer(newSource.getRenderedImage().getWidth()));
				session.setAttribute(WebappConstants.CONTENT_IMAGE_NEW_HEIGHT_KEY, new Integer(newSource.getRenderedImage().getHeight()));
			} catch ( Exception ex ) {
				if ( formFile != null ) {
					formFile.destroy();
				}
				session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);

				ActionMessages errors = new ActionMessages();
				errors.add("contentResourceCorruptedData", new ActionMessage("core.contentResource.errors.corruptedData"));
				saveErrors(request, errors);
				return mapping.findForward("callUpdateContentResource");
			}

			session.setAttribute(WebappConstants.CONTENT_IMAGE_NEW_MIMETYPE_KEY, mimeType);
			session.setAttribute(WebappConstants.CONTENT_IMAGE_NEW_SIZE_KEY, new Long(formFile.getFileData().length));
			session.setAttribute(WebappConstants.CONTENT_IMAGE_NEW_FILENAME_KEY, formFile.getFileName());

		} else {
			session.removeAttribute(WebappConstants.CONTENT_IMAGE_NEW_MIMETYPE_KEY);
			session.removeAttribute(WebappConstants.CONTENT_IMAGE_NEW_SIZE_KEY);
			session.removeAttribute(WebappConstants.CONTENT_IMAGE_NEW_FILENAME_KEY);
		}

		// Populate content locale list
		List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
		session.setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);

        saveToken(request);
		return mapping.findForward("updateImage");
	}

}